<template>
  <div class="content">
    <div class="head">
      <div class="headCard">
        <div class="cardText">
          <div class="areaName">{{item.cinemaName}}</div>
          <div class="areaAddress">{{item.address}}</div>
        </div>
        <img @click="show = true" class="icon8" src="../../../static/icon8.png" alt="" />
      </div>
      <van-action-sheet v-model="show" :actions="actions" cancel-text="取消" close-on-click-action @select="mapSelect" />
      <swiper :options="swiperOption" ref="mySwiper" @slideChange="slideChange" v-if="imgList.length>0">
          <swiper-slide v-for="(item,index) in imgList" :key="index">
            <img class="slideImg" :src="item.cover" alt=""  />
          </swiper-slide>
      </swiper>
      <div class="filmName">{{filmName+' '}}<span style="color: #FF6060;">{{preSaleFlag==0?(filmScore==0?'暂无评分':filmScore):Math.floor(wantview/10000)+'万人想看'}}</span></div>
    </div>
    <div class="filmDetail">
        <div class="filmTip">{{durationType}}</div>
        <div class="vanTab">
          <van-tabs v-model="active" @change='tabChange' :ellipsis='false'>
            <van-tab v-for="(item,index) in dayList" :key="index" :title="item.showTime"></van-tab>
          </van-tabs>
        </div>
    </div>
    <div class="list" v-for="(item,index) in bottomList" :key="index">
      <div class="time">
        <div class="timeStart">{{item.start}}</div>
        <div class="timeEnd">{{item.end}}散场</div>
      </div>
      <div class="time">
        <div class="timeStart">{{item.copyLanguage}} {{item.copyType}}</div>
        <div class="timeEnd">{{item.hallName}}</div>
      </div>
      <div class="price">{{item.minPrice}}起</div>
      <div class="button" @click="gotoClientPresent(item.featureAppNo)">选座</div>
    </div>

    <div class="popup" v-if="showpopup" round>
      <div class="popups">
        <div class="changePhonePage">
          <div class="changePhoneTitle">{{ title }}</div>
          <van-row class="changePhoneView" style="">
            <van-field v-model="newPhone" label="手机号码" placeholder="请输入手机号码" />
          </van-row>
          <van-row class="changePhoneView">
            <van-cell-group inset>
              <van-field v-model="captcha" placeholder="请输入图形验证码">
                <template #button>
                  <img class="uuidImg" :src="imgUrl" @click="uuidClick" />
                </template>
              </van-field>
            </van-cell-group>
          </van-row>
          <van-row class="changePhoneView" style="margin-left: 20px;">
            <van-col class="smsCodeView">
              <van-field v-model="smsCode" label="验证码" placeholder="验证码" />
            </van-col>
            <van-col class="smsCodeText">
              <span class="smsCodeSpan" v-show="!showCountDown" @click="getSms">获取验证码</span>
              <van-count-down
                v-show="showCountDown"
                ref="countDown"
                :auto-start="false"
                @finish="countDownFinish"
                :time="time"
                format="ss秒"
                style="line-height: .64rem;color:#ff5500;"
              />
            </van-col>
          </van-row>
          <div class="changePhoneButVuew">
            <!-- <div class="changePhoneCancel" @click="phoneCancel">取消</div> -->
            <div class="changePhoneBut" @click="beforeClose">提交</div>
          </div>
        </div>
      </div>

    </div>


  </div>
</template>
<script>
import { baseApi } from '@/config'
import {
  setStore,
  getStore,
  removeStore
} from '@/utils/storage'
import { map } from 'qqmap';
import wx from 'weixin-js-sdk'
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import {getFilmList,getPlan,cinemaPlanDate,smsCode,bindMobile,userInfo} from '@/api/home.js'
import { Tab, Tabs } from 'vant';
export default {
  name: 'cinemaDetail',
  components: {
    // 注册 vue-awesome-swiper 组件
    swiper,
    swiperSlide
  },
 data(){
    let realIndex
    return{
      swiperOption: {
          spaceBetween: 40,
          slidesPerView: 4.2, // 一屏显示的slide个数
          centeredSlides: true,// 居中的slide是否标记为active，默认是最左active,这样样式即可生效
          slideToClickedSlide: true,// 点击的slide会居中
          loop: false,// 循环播放, 可有无限滚动效果，初始加载即是滚动后的效果
          on: {
              // 该方法中的this都指代swiper本身
              tap: function () {
                realIndex = this.realIndex
              }
          }
      },
      index:'',
      imgList:[
      ],
      active:0,
      item:{},
      activeIndex:0 ,// 轮播图数据列表下标
      filmName:'',
      filmScore:'',
      durationType:'',
      dayList:[],
      bottomList:[],
      actions: [
        {
          name: '腾讯地图'
        },
        {
          name: '高德地图'
        },
        {
          name: '百度地图'
        }
      ],
      fromBottomBoxMsg:[],
      show: false,
      updatePhoneShow: true,
      newPhone: '',
      smsCode: '',
      time: 60000,
      showCountDown: false,
      captcha: '',
      uuid: '',
      imgUrl: '',
      title: '绑定手机号码',
      showpopup:false,
      time:0,
      preSaleFlag:'',
      wantview:''
	 }
	},
  mounted() {
    this.item = JSON.parse(this.$route.query.item)
    console.log(this.item)
    this.getFilmList()
     this.uuidImgData()
  },
	methods:{
    // 轮播图滑动事件
    slideChange(){
      this.activeIndex = this.$refs.mySwiper.swiper.realIndex
      this.filmName = this.imgList[this.activeIndex].filmName
      this.filmScore = this.imgList[this.activeIndex].score/100
      this.preSaleFlag = this.imgList[this.activeIndex].preSaleFlag
      this.wantview = this.imgList[this.activeIndex].wantview
      this.durationType = this.imgList[this.activeIndex].duration+'分钟'+'/'+this.imgList[this.activeIndex].type
      this.cinemaPlanDate(this.activeIndex)
    },
    test(e) {
        // 默认会$event对象
        console.log(11,e);
    },
    gotoClientPresent(featureAppNo){
      if(JSON.parse(getStore('userInfo')).mobile){
        this.$router.push({
          path:'/clientPresent?cinemaId='+this.item.cinemaId+'&featureAppNo='+featureAppNo
        })
      }else{

        this.showpopup = true
      }


    },
    // 影片列表
    getFilmList(){
      let data = {
        publishFlag:0,
        cinemaId:this.item.cinemaId,
        limit:99999
      }
      getFilmList(data).then(res=>{
        this.imgList = res.page.records
        this.filmName = res.page.records[0].filmName
        this.filmScore = res.page.records[0].score/100
        this.durationType = res.page.records[0].duration+'分钟'+'/'+res.page.records[0].type
        this.cinemaPlanDate(0)
      })
    },
    //获取影院排期日期
    cinemaPlanDate(index){
      console.log(index,this.imgList)
      let data = {
        cityId:this.item.cityId,
        filmCode:this.imgList[index].filmCode,
        cinemaId:this.item.cinemaId
      }
      cinemaPlanDate(data).then(res=>{
        let list = res.list
        this.dayList = this.groupBy(list)
        this.getPlan(index,this.time)
      })
    },
    groupBy(list) {
      let arrList = []
      list.forEach((item,index)=>{
        let time = new Date(item*1000)
        arrList.push({
          startTime:time.getFullYear()+'-'+(time.getMonth() + 1)+"-"+time.getDate(),
          showTime:this.getWeekday(time)+(time.getMonth() + 1)+ "月"+time.getDate()+"日"
        })
      });
      return arrList
    },
    getWeekday(date) {
      const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
      const now = new Date();
      const dayIndex = date.getDay();

      now.setHours(0, 0, 0, 0);
      date.setHours(0, 0, 0, 0);

      const dayDifference = (date - now) / (1000 * 60 * 60 * 24);

      if (dayDifference === 0) {
          return '今天';
      } else if (dayDifference === 1) {
          return '明天';
      } else if (dayDifference === 2) {
          return '后天';
      } else {
          return weekdays[dayIndex];
      }
    },
    // 选着日期
    tabChange(e){
      this.getPlan(this.activeIndex,e)
      this.time = e
    },
    getPlan(index,time){
      let data = {
        filmCode:this.imgList[index].filmCode,
        cinemaId:this.item.cinemaId,
        startTime:this.dayList[time].startTime,
        limit:99999
      }
      getPlan(data).then(res=>{
        let list = res.page.records
        list.forEach((item,index)=>{
          item.start = this.bottomStart(item.startTime)
          item.end = this.bottomEnd(item.startTime,item.totalTime)
        })
        this.bottomList = list
      })
    },
    bottomStart(time){
      let datetime = new Date(time*1000)
      let date = (datetime.getHours()=='00'?'00':(datetime.getHours()<10?'0'+datetime.getHours():datetime.getHours()))+':'+(datetime.getMinutes()=='00'?'00':(datetime.getMinutes()<10?'0'+datetime.getMinutes():datetime.getMinutes()));
      return date;
    },
    bottomEnd(start,end){
      let dateEnd = new Date(start*1000+end*60000)
      let date = (dateEnd.getHours()=='00'?'00':(dateEnd.getHours()<10?'0'+dateEnd.getHours():dateEnd.getHours()))+':'+(dateEnd.getMinutes()=='00'?'00':(dateEnd.getMinutes()<10?'0'+dateEnd.getMinutes():dateEnd.getMinutes()));
      return date;
    },
    mapSelect(item) {
      this.fromBottomBoxMsg = new TMap.LatLng(Number(JSON.parse(getStore('addressInfo')).location.lat), Number(JSON.parse(getStore('addressInfo')).location.lng))
      this.onClick(item.name)
    },
    onClick(name) {
      var destination = new Array(this.fromBottomBoxMsg.lat.toFixed(6), this.fromBottomBoxMsg.lng.toFixed(6)) // 获取vuex中的想去目的地的经纬度参数
      var u = navigator.userAgent // 判断是android系统还是IOS系统
      var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
      var Destination = this.item.cinemaName
      if (name == '高德地图') {
        if (isAndroid == true) {
          location.href =
            'https://uri.amap.com/marker?position=' +
            destination[1] +
            ',' +
            destination[0] +
            '&name=' +
            Destination +
            '&callnative=1'
        } else {
          location.href =
            'https://uri.amap.com/marker?position=' +
            destination[1] +
            ',' +
            destination[0] +
            '&name=' +
            Destination +
            '&callnative=1'
        }
      } else if (name == '百度地图') {
        if (isAndroid == true) {
          location.href =
            'http://api.map.baidu.com/geocoder?location=' +
            this.fromBottomBoxMsg.lat +
            ',' +
            this.fromBottomBoxMsg.lng +
            '&src=webapp.baidu.openAPIdemo&coord_type=gcj02&output=html'
        } else {
          location.href =
            'http://api.map.baidu.com/geocoder?location=' +
            this.fromBottomBoxMsg.lat +
            ',' +
            this.fromBottomBoxMsg.lng +
            '&src=webapp.baidu.openAPIdemo&coord_type=gcj02&output=html'
        }
      } else if (name == '腾讯地图') {
        if (isAndroid == true) {
          location.href =
            'https://apis.map.qq.com/uri/v1/marker?marker=coord:' +
            destination[0] +
            ',' +
            destination[1] +
            ';title:' +
            this.item.cinemaName +
            ';addr:' +
            this.item.address +
            '&referer=myapp'
        } else {
          location.href =
            'https://apis.map.qq.com/uri/v1/marker?marker=coord:' +
            destination[0] +
            ',' +
            destination[1] +
            ';title:' +
            this.item.cinemaName +
            ';addr:' +
            this.item.address +
            '&referer=myapp'
        }
      }
    },
    onDataSubmit(e) {
    	if (!this.mobile) {
    		this.showDialog('请输入手机号码')
    		return
    	}
    	if (!this.code) {
    		this.showDialog('请输入验证码')
    		return
    	}

    },

    getUUID() {
      return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {
        return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
      })
    },
    uuidImgData() {
      this.uuid = this.getUUID()
      this.imgUrl = baseApi + '/captcha.jpg?uuid=' + this.uuid + '&token=' + this.$getStore('token')
      console.log(this.imgUrl)
    },
    uuidClick() {
      this.uuidImgData()
    },
    phoneCancel() {
      this.cancelData()
      this.$emit('phoneCancel')
    },
    countDownFinish() {
      this.time = 60000
      this.showCountDown = false
      this.$refs.countDown.reset()
    },
    cancelData() {
      this.newPhone = ''
      this.captcha = ''
      this.uuid = ''
      this.uuidImgData()
    },
    getSms() {
      if (!/^1[3456789]\d{9}$/.test(this.newPhone)) {
        this.showToast('请输入正确的手机号码')
        return false
      }
      if (!this.captcha) {
        this.showToast('请输入图形验证码')
        return false
      }
      const data = {
        phone: this.newPhone,
        code: this.captcha,
        uuid: this.uuid,
        configId: 'note_code'
      }
      smsCode(data)
        .then(res => {
          if (res.code === 0) {
            this.showToast(res.msg)
            this.$refs.countDown.start()
            this.showCountDown = true
          } else {
            this.showToast(res.msg)
            this.uuidImgData()
          }
        })
        .catch(res => {
          this.cancelData()
          this.showToast(res.msg)
        })
    },
    beforeClose() {
      // 点击的是确认按钮
      // 校验手机号码
      if (!/^1[3456789]\d{9}$/.test(this.newPhone)) {
        this.showToast('请输入正确的手机号码')
        return false
      }
      if (!this.captcha) {
        this.showToast('请填写图形验证码')
        return false
      }
      if (!this.smsCode) {
        this.showToast('请填写短信验证码')
        return false
      }
      // 请求修改接口
      const data = {
        phone: this.newPhone,
        code: this.smsCode,
      }
      bindMobile(data)
        .then(res => {
          if (res.code == 0) {
            this.showToast(res.msg)
            this.showpopup = false
            setTimeout(()=>{
              userInfo().then(res=>{
                setStore('userInfo', res.data)
              })
            },1000)
            this.$forceUpdate()
          }
        })
        .catch(res => {
          this.showToast(res.msg)
          this.smsCode = ''
          this.cancelData()

        })
    },
    showToast(msg) {
      this.$toast({
        message: msg,
        position: 'center',
        duration: 2500
      })
    }
	}
}
</script>

<style lang="less" scoped>
.content{
  width: 100vw;
  min-height: 100vh;
  background-color: #EBF2FC;
  box-sizing: border-box;
  padding-bottom: 50px;
  .head{
    width: 375px;
    height: 320px;
    background: url('../../../static/icon7.png') no-repeat;
    background-size: 100% 100%;
    overflow: hidden;
    .headCard{
      width: 353px;
      height: 89px;
      background: #FFFFFF;
      border-radius: 5px 5px 5px 5px;
      margin: 20px auto 30px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 16px;
      box-sizing: border-box;
      .cardText{
        width: 280px;
        .areaName{
          font-weight: bold;
          font-size: 17px;
          color: #333333;
        }
        .areaAddress{
          font-weight: 500;
          font-size: 12px;
          color: #737373;
          margin-top: 10px;
        }
      }
      .icon8{
        display: block;
        width: 34px;
        height: 34px;
      }
    }
    .filmName{
      font-weight: 500;
      font-size: 20px;
      color: #333333;
      text-align: center;
    }
  }
  .filmDetail{
    width: 100%;
    height: 75px;
    background-color: #fff;
    margin-bottom: 15px;
    .filmTip{
      width: 100%;
      height: 18px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 14px;
      color: #AFAFAF;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      text-align: center;
    }
    .vanTab{
      margin-top: 20px;
      ::v-deep .van-tabs__line{
        background-color: #1484FB !important;
      }
    }
  }
  .list{
    width: 353px;
    min-height: 78px;
    background-color: #fff;
    margin: 10px auto;
    border-radius: 7px 7px 7px 7px;
    display: flex;
    align-items: center;
    padding: 5px;
    .time{
      width: 70px;
      margin-left: 12px;
      overflow: hidden;
      text-align: center;
      .timeStart{
        font-weight: 500;
        font-size: 18px;
        color: #333333;
        line-height: 20px;
        text-align: center;
      }
      .timeEnd{
        font-weight: 400;
        font-size: 14px;
        color: #AFAFAF;
        margin-top: 5px;
        text-align: center;
      }
    }
    .price{
      width: 60px;
      font-weight: 500;
      font-size: 18px;
      color: #FF6060;
      margin-left: 18px;
      text-align: center;
    }
    .button{
      width: 69px;
      height: 32px;
      background-color: #1484FB;
      text-align: center;
      line-height: 32px;
      font-size: 15px;
      color: #FFFFFF;
      margin-left: 20px;
    }
  }



  .swiper {
      width: 100%;
      height: 150px;
      bottom: 10px;
      position: absolute;
  }

  .swiper-container {
      width: 100%;
      // height: 100%;
      overflow: visible !important;
  }
  .swiper-slide {
      text-align: center;
      font-size: 18px;
      height: 150px;
      width: 106px;
      /* Center slide text vertically */
      display: -webkit-box;
      display: -ms-flexbox;
      display: -webkit-flex;
      display: flex;
      -webkit-box-pack: center;
      -ms-flex-pack: center;
      -webkit-justify-content: center;
      justify-content: center;
      -webkit-box-align: center;
      -ms-flex-align: center;
      -webkit-align-items: center;
      align-items: center;
      transition: 300ms;
      // transform: scale(.8);
      .slideImg{
        display: block;
        width: 84.8px;
        height: 120px;
      }
  }

  .swiper-slide-active,
  .swiper-slide-duplicate-active {
      transform: scale(1);
      position: relative;
      margin-left: 10px;
      margin-right: 50px !important;
      .slideImg{
        display: block;
        width: 106px;
        height: 150px;
        position: absolute;
        bottom: 15px;
      }
  }
  .changePhoneCancel {
    width: 110px;
    height: 30px;
    font-size: 15px;
    text-align: center;
    letter-spacing: 2px;
    font-weight: bold;
    background: #cdcdcd;
    border-radius: 15px;
    line-height: 30px;
    color: #fff;
    margin-right: 40px;
  }
  .changePhoneButVuew {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .changePhoneBut {
    width: 110px;
    height: 30px;
    font-size: 15px;
    text-align: center;
    letter-spacing: 2px;
    font-weight: bold;
    background: #3289fe;
    border-radius: 15px;
    line-height: 30px;
    color: #fff;
    margin-top: 40px;
  }
  .smsCodeSpan {
    background-color: #ff5500;
    color: #ffffff;
    font-size: 13px;
    float: right;
    padding: 4px;
    line-height: 0.64rem;
  }
  .smsCodeText {
    width: 30%;
    padding-right: 10px;
    padding-top: 10px;
  }
  .smsCodeView {
    width: 70%;
  }
  .changePhoneView {
    margin-top: 6px;
    margin-bottom: 6px;
  }
  .uuidImg{
    width: 100px;
    margin-left: 20px;
  }
  .changePhoneTitle {
    font-size: 16px;
    color: #333;
    text-align: center;
    margin-top: 10px;
    font-weight: bold;
  }
  .changePhonePage {
    width: 320px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .popup{
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, .3);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    overflow: hidden;
  }
  .popups{
    width: 350px;
    height: 300px;
    background-color: #fff;
    border-radius: 25px;
    margin: 150px auto 0;
  }
}
</style>
